package com.ad.aidai.fragments.order.order_nearby;

import android.content.Context;
import android.view.ViewGroup;

import com.ad.aidai.R;
import com.ad.aidai.bean.Order;
import com.ad.aidai.common.ADApp;
import com.ad.aidai.network.NetWork;
import com.ad.aidai.network.StatusCodeFromNet;
import com.ad.aidai.network.result.GetOrderListFromNet;
import com.ad.aidai.viewholder.OrderThreeLineViewHolder;
import com.ad.aidai.viewholder.OrderViewHolder;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * OrderNearbyPresenter
 * <p>
 * Created by Yusxon on 16/12/19.
 */

public class OrderNearbyPresenter implements OrderNearbyContract.Presenter, RecyclerArrayAdapter
        .OnMoreListener, RecyclerArrayAdapter.OnNoMoreListener {

    private Context mContext;
    private OrderNearbyContract.View mView;
    /**
     * view的设配器
     */
    private RecyclerArrayAdapter<Order> orderAdapter;

    /**
     * 当前是否在刷新
     */
    private boolean isRefreshing = false;

    /**
     * 最多显示一次加载多少数据
     */
    private static final int PAGE_SIZE = 10;

    /**
     * 当前加载第几页
     */
    private int currentPage = 1;

    /**
     * 是否有设置定位,默认为false
     */
    private boolean isSetLocation = false;

    public OrderNearbyPresenter(Context context, OrderNearbyContract.View view) {
        this.mContext = context;
        this.mView = view;
        mView.setPresenter(this);
        orderAdapter = new RecyclerArrayAdapter<Order>(mContext) {

            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                if (viewType == Order.STATUS_NO_RECIEVE) {
                    return new OrderThreeLineViewHolder(parent);
                }
                return new OrderViewHolder(parent);
            }

            @Override
            public int getViewType(int position) {
                return mObjects.get(position).getOrderStatus();
            }
        };
        listener();
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unSubscribe() {
        mContext = null;
        mView = null;
    }

    @Override
    public RecyclerArrayAdapter<Order> getAdapter() {
        return orderAdapter;
    }

    @Override
    public void refresh() {
        refreshOrders();
    }

    private Map<String, String> getMaps(int currentPage) {
        Map<String, String> maps = new HashMap<>();
        maps.put("pageSize", String.valueOf(PAGE_SIZE));
        maps.put("currentPage", String.valueOf(currentPage));
        maps.put("placeLongtitude", String.valueOf(ADApp.getUserLongtitude()));
        maps.put("placeLatitude", String.valueOf(ADApp.getUserLatitude()));
        maps.put("userId", String.valueOf(ADApp.getUser().getUserId()));

        return maps;
    }

    /**
     * 刷新订单
     */
    private void refreshOrders() {
        isRefreshing = true;
        NetWork.getOrderOperationApi()
                .getNearByOrderList(getMaps(1))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<GetOrderListFromNet>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        MobclickAgent.reportError(mContext, e);
                        Logger.t("OrderNearbyPresenter").e(e.getMessage());
                        mView.toast("刷新失败");
                        isRefreshing = false;
                        orderAdapter.add(null);
                    }

                    @Override
                    public void onNext(GetOrderListFromNet result) {
                        isRefreshing = false;
                        if (result.getCode() == StatusCodeFromNet.CODE_SUCCESS) {
                            Logger.t("OrderNearbyPresenter").i(result.toString());
                            List<Order> orders = result.getData();
                            Logger.t("OrderNearbyPresenter").i(orders.size() + "--");
                            currentPage = 2;
                            orderAdapter.clear();
                            orderAdapter.addAll(orders);
                            orderAdapter.stopMore();
                        } else {
                            mView.toast("刷新失败");
                            orderAdapter.add(null);
                            Logger.t("OrderNearbyPresenter").e(result.toString());
                        }
                    }
                });
    }

    /**
     * 加载订单
     */
    private void loadMoreOrders() {
        Logger.i("loadMoreOrders");
        NetWork.getOrderOperationApi()
                .getNearByOrderList(getMaps(currentPage))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<GetOrderListFromNet>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        MobclickAgent.reportError(mContext, e);
                        Logger.t("OrderNearbyPresenter").e(e.getMessage());
                        mView.toast("加载失败");
                        orderAdapter.stopMore();
                    }

                    @Override
                    public void onNext(GetOrderListFromNet result) {
                        if (result.getCode() == StatusCodeFromNet.CODE_SUCCESS) {
                            Logger.t("OrderNearbyPresenter").i(result.toString());
                            List<Order> orders = result.getData();
                            Logger.t("OrderNearbyPresenter").i(orders.size() + "--");
                            currentPage++;
                            orderAdapter.insertAll(orders, orderAdapter.getCount());
                            if (orders.size() == 0) {
                                //暂停加载,暂时改为,停止下载则底部变成没有更多了且不可以点击
                                orderAdapter.pauseMore();
                            } else {
                                //停止加载,底部变为点击加载更多
                                orderAdapter.stopMore();
                            }
                        } else {
                            mView.toast("加载失败");
                            Logger.t("OrderNearbyPresenter").e(result.toString());
                            //停止加载,底部变为点击加载更多
                            orderAdapter.stopMore();
                        }
                    }
                });
    }

    /**
     * 设置各种监听
     */
    private void listener() {
        //加载更多
        orderAdapter.setMore(R.layout.view_more, this);
        //没有更多
        orderAdapter.setNoMore(R.layout.view_clickmore, this);
        //加载错误(原来的逻辑有问题,暂时只能用没有更多来代替)
        orderAdapter.setError(R.layout.view_nomore);

        orderAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                ADApp.setOrder(orderAdapter.getItem(position));
                mView.intoItem();
            }
        });
    }

    @Override
    public void onMoreShow() {
        if (!isRefreshing) {
            loadMoreOrders();
        } else {
            //            Logger.t(this.getClass().getSimpleName()).i("onMoreShow");
            orderAdapter.stopMore();
        }
    }

    @Override
    public void onMoreClick() {
    }

    @Override
    public void onNoMoreShow() {
        //        Logger.t(this.getClass().getSimpleName()).i("onNoMoreShow");
        orderAdapter.resumeMore();
    }

    @Override
    public void onNoMoreClick() {
        //        Logger.t(this.getClass().getSimpleName()).i("onNoMoreClick");
        orderAdapter.resumeMore();
    }

    @Override
    public void orderStatusChange(Order order) {
        if (orderAdapter != null && orderAdapter.getCount() > 0) {
            int position = 0;
            for (Order oldOrder : orderAdapter.getAllData()) {
                if (oldOrder.getOrderId() == order.getOrderId()) {
                    orderAdapter.remove(position);
                    if(order.getOrderStatus() != Order.STATUS_CANCEL) {
                        orderAdapter.insert(order, position);
                    }
                    break;
                }
                position++;
            }
        }
    }
}
